use actix::{Actor, StreamHandler};
use actix_web::{HttpResponse, web, HttpRequest, Error};
use actix_web_actors::ws;

/// Define HTTP actor
struct MyWs;

impl Actor for MyWs {
    type Context = ws::WebsocketContext<Self>;
}

/// Handler for ws::Message message
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
    fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
        match msg {
            Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
            Ok(ws::Message::Text(text)) => ctx.text(text),
            Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
            _ => (),
        }
    }
}

pub async fn socket_handler(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
    let addr =req.peer_addr().unwrap_or_else(|| "unknown".parse().unwrap());
    println!("sec-websocket-key: {:?} addr: {:?}", req.headers().get("sec-websocket-key"), addr);
    let resp = ws::start(MyWs {}, &req, stream);
    println!("{:?}", resp);
    resp
}